package de.streblow.inventur;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

	private Socket client;
	private DataOutputStream dataOutputStream;
	private DataInputStream dataInputStream;
	private String datablock;

	 @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		final Button button1 = (Button) findViewById(R.id.buttonStartInventury);
		button1.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, InputActivity.class);
				TextView tvteamID = (TextView) findViewById(R.id.editTeamID);
				if (tvteamID.getText().toString().isEmpty()) {
					return;
				}
				intent.putExtra("teamID", tvteamID.getText().toString());
				startActivity(intent);
			}
		});

		final Button button2 = (Button) findViewById(R.id.buttonSubmit);
		button2.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				final TextView tvIPAddress = (TextView) findViewById(R.id.editIPAddress);
				final TextView tvPort = (TextView) findViewById(R.id.editPort);
				final TextView tvteamID = (TextView) findViewById(R.id.editTeamID);
				if (tvIPAddress.getText().toString().isEmpty() |
						tvPort.getText().toString().isEmpty() |
						tvteamID.getText().toString().isEmpty()) {
					return;
				}
				Thread networkThread = new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							client = new Socket();
							client.connect(new InetSocketAddress(tvIPAddress.getText().toString(), Integer.parseInt(tvPort.getText().toString())), 10000); //connect to server
							dataOutputStream = new DataOutputStream(client.getOutputStream());
							dataOutputStream.writeUTF(tvteamID.getText().toString()); //send teamID
							dataInputStream = new DataInputStream(client.getInputStream());
							datablock = dataInputStream.readUTF(); //get response (ok... or error...)
							if (datablock.substring(0, 2).equalsIgnoreCase("ok")) {
								File filesDir = getFilesDir();
								File fInventurfile = new File(filesDir, tvteamID.getText().toString());
								FileInputStream fisInventurfile;
								InputStreamReader isrInventurfile;
								BufferedReader brInventurfile;
								String line = "";
								ArrayList<String> lines = new ArrayList<String>();
								try {
									fisInventurfile = new FileInputStream(fInventurfile);
									isrInventurfile = new InputStreamReader(fisInventurfile);
									brInventurfile = new BufferedReader(isrInventurfile);
									while ((line = brInventurfile.readLine()) != null) {
										lines.add(line);
									}
									for (int i = 0; i < lines.size(); i++) {
										dataOutputStream.writeUTF(lines.get(i));
										datablock = dataInputStream.readUTF(); //get response (ok... or error...)
										if (datablock.substring(0, 2).equalsIgnoreCase("ok")) {
											lines.set(i, "");
										}
									}
									dataOutputStream.writeUTF(""); //signal end of submission
									dataOutputStream.close();
									dataInputStream.close();
									fisInventurfile.close();
								} catch (Exception e) {
									e.printStackTrace();
								} finally {
									//delete all records that are empty in the local stored file
									FileOutputStream fosInventurfile;
									fInventurfile.delete();
									fosInventurfile = openFileOutput(tvteamID.getText().toString(), Context.MODE_APPEND);
									for (int i = 0; i < lines.size(); i++) {
										try {
											if (!lines.get(i).equalsIgnoreCase("")) {
												fosInventurfile.write(lines.get(i).getBytes());
												fosInventurfile.write(new String("\n").getBytes());
											}
										} catch (IOException e) {
											Messagebox.showMessagebox(MainActivity.this, "Error!", e.getMessage());
										}
									}
								}
							} else {
								datablock = "error - access denied";
							}
						} catch (UnknownHostException e) {
							e.printStackTrace();
							datablock = "error - host unknown";
						} catch (IOException e) {
							e.printStackTrace();
							datablock = "error - I/O";
						} finally{
							if (client != null){
								try {
									client.close();
								} catch (IOException e) {
									e.printStackTrace();
								}
							}
						}
					}
				});
				networkThread.start();
				try {
					networkThread.join();
					if (datablock.substring(0, 2).equalsIgnoreCase("ok")) {
						Messagebox.showMessagebox(MainActivity.this, getString(R.string.submission_result_title), getString(R.string.submission_result_ok));
					} else {
						Messagebox.showMessagebox(MainActivity.this, getString(R.string.submission_result_title), getString(R.string.submission_result_error));
					}
				} catch (InterruptedException e) {
				}
			}
		});

		final Button button3 = (Button) findViewById(R.id.buttonTest);
		button3.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				final TextView tvIPAddress = (TextView) findViewById(R.id.editIPAddress);
				final TextView tvPort = (TextView) findViewById(R.id.editPort);
				final TextView tvteamID = (TextView) findViewById(R.id.editTeamID);
				if (tvIPAddress.getText().toString().isEmpty() |
						tvPort.getText().toString().isEmpty() |
						tvteamID.getText().toString().isEmpty()) {
					return;
				}
				Thread networkThread = new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							client = new Socket();
							client.connect(new InetSocketAddress(tvIPAddress.getText().toString(), Integer.parseInt(tvPort.getText().toString())), 10000); //connect to server
							dataOutputStream = new DataOutputStream(client.getOutputStream());
							dataOutputStream.writeUTF(tvteamID.getText().toString()); //send teamID
							dataInputStream = new DataInputStream(client.getInputStream());
							datablock = dataInputStream.readUTF(); //get response (ok... or error...)
							if (datablock.substring(0, 2).equalsIgnoreCase("ok")) {
								try {
									for (int i = 0; i < 2000; i++) {
										dataOutputStream.writeUTF("90000000;X-01-03;" + Integer.toString(i) + ";Stck.");
										datablock = dataInputStream.readUTF(); //get response (ok... or error...)
										if (!datablock.substring(0, 2).equalsIgnoreCase("ok")) {
											datablock = "error - submission failed";
											break;
										}
									}
									dataOutputStream.writeUTF(""); //signal end of submission
									dataOutputStream.close();
									dataInputStream.close();
								} catch (Exception e) {
									e.printStackTrace();
								} finally {
								}
							} else {
								datablock = "error - access denied";
							}
						} catch (UnknownHostException e) {
							e.printStackTrace();
							datablock = "error - host unknown";
						} catch (IOException e) {
							e.printStackTrace();
							datablock = "error - I/O";
						} finally{
							if (client != null){
								try {
									client.close();
								} catch (IOException e) {
									e.printStackTrace();
								}
							}
						}
					}
				});
				networkThread.start();
				try {
					networkThread.join();
					if (datablock.substring(0, 2).equalsIgnoreCase("ok")) {
						Messagebox.showMessagebox(MainActivity.this, getString(R.string.submission_result_title), getString(R.string.submission_result_ok));
					} else {
						Messagebox.showMessagebox(MainActivity.this, getString(R.string.submission_result_title), getString(R.string.submission_result_error));
					}
				} catch (InterruptedException e) {
				}
			}
		});

		TextView tvIPAddress = (TextView) findViewById(R.id.editIPAddress);
		tvIPAddress.setFocusableInTouchMode(true);
		tvIPAddress.requestFocus();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		//inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
		case R.id.action_settings:
			Intent intent = new Intent(MainActivity.this, OptionsActivity.class);
			startActivity(intent);
			return true;
		case R.id.action_help:
			HelpDialog help = new HelpDialog(this);
			help.setTitle(R.string.help_title);
			help.show();
			return true;
		case R.id.action_about:
			AboutDialog about = new AboutDialog(this);
			about.setTitle(R.string.about_title);
			about.show();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

}
